package cn.changhong.user.service.impl;

import cn.changhong.user.aop.ResultBean;
import cn.changhong.user.dao.AuthenticationMapper;
import cn.changhong.user.dao.RoleAuthenticationMapper;
import cn.changhong.user.dao.UserMapper;

import cn.changhong.user.exception.UserException;
import cn.changhong.user.exception.WrongPasswordException;
import cn.changhong.user.model.*;
import cn.changhong.user.model.vo.ListUserVO;
import cn.changhong.user.model.vo.UserVO;
import cn.changhong.user.service.UserService;
import cn.changhong.user.util.TokenAuthenticationService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Properties;

/**
 * @Author zz
 * @Date
 **/
@Service
public class UserServiceImpl implements UserService {
    private final String REGISTER_OK="register success";
    private final String EMAIL_EXISTS="email address already used";
    @Autowired
    UserMapper userMapper;
    @Autowired
    RoleAuthenticationMapper roleAuthenticationMapper;
    @Autowired
    AuthenticationMapper authenticationMapper;

    @Override
    public User login(String email, String password) {
        UserExample userExample=new UserExample();
        userExample.createCriteria().andEmailEqualTo(email).andPasswordEqualTo(password);
        List<User> list=userMapper.selectByExample(userExample);
        if(list.size() == 0) {
            return null;
        }
        return list.get(0);
    }

    @Override
    public ResultBean register(String email,String password) {
        User user=new User();
        user.setEmail(email);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        user.setStatus(1);
        user.setRoleId(2);
        user.setSex(1);
        user.setPassword(password);
        UserExample userExample=new UserExample();
        userExample.createCriteria().andEmailEqualTo(email);

        try {
            userMapper.updateByExampleSelective(user,userExample);
            return new ResultBean();
        }catch (DuplicateKeyException e){
            return new ResultBean(e,ResultBean.CONFLICT);
        }
    }

    @Override
    public ResultBean<ListUserVO> listUserByPage(int currentPage,int pageSize) {
        //分页核心就此一句
        PageHelper.startPage(currentPage, pageSize);
        UserExample userExample=new UserExample();
        List<User> list=userMapper.selectByExample(userExample);


        ListUserVO listUserVO=new ListUserVO();
        listUserVO.setUserList(list);
        listUserVO.setCount((int)userMapper.countByExample(userExample));
        return new ResultBean<>(listUserVO);
    }

    @Override
    public int removeUser(String email){
        UserExample userExample=new UserExample();
        userExample.createCriteria().andEmailEqualTo(email);
        return userMapper.deleteByExample(userExample);
    }

    @Override
    public int freezeUser(String email) {
        User user=new User();
        UserExample userExample=new UserExample();
        userExample.createCriteria().andEmailEqualTo(email);
        User user1=userMapper.selectByExample(userExample).get(0);
        if(user1.getStatus() == 1){
            user.setStatus(2);
        }else {
            user.setStatus(1);
        }
        return userMapper.updateByExampleSelective(user,userExample);
    }

    @Override
    public int resetPassword(Long userId,String password) {
        User user=new User();
        user.setPassword(password);
        UserExample userExample=new UserExample();
        userExample.createCriteria().andIdEqualTo(userId);
        return userMapper.updateByExampleSelective(user,userExample);
    }

    @Override
    public ResultBean forgetPassword(String email) {
        try {
            Session session = CreateSession();
            Transport ts = session.getTransport();
            String content="请联系管理员：375359554@qq.com";
            ts.connect("smtp.qq.com","375359554@qq.com","orfgypplgcoibjei");
            String[] to={email};
            Message message = createSimpleMail(session,"375359554@qq.com",to,"长虹智能手环",content);
            ts.sendMessage(message, message.getAllRecipients());
        }catch (Exception e){
            return new ResultBean(e,ResultBean.CONFLICT);
        }

        return new ResultBean();
    }

    @Override
    public UserVO getUser(HttpServletRequest request) {
        Authentication authentication=TokenAuthenticationService.getAuthentication(request);
        String email=authentication.getPrincipal().toString();
        UserExample example=new UserExample();
        example.createCriteria().andEmailEqualTo(email);
        List<User> list=userMapper.selectByExample(example);
        if(list.size() == 0){
            return null;
        }

        User user=list.get(0);
        String role;
        if(user.getRoleId() == 1){
            role="SuperAdmin";
        }else if(user.getRoleId() == 2){
            role="Admin";
        }else {
            role="CommonUser";
        }

        UserVO userVO=new UserVO();
        userVO.setAvatar(user.getAvatar());
        userVO.setId(user.getId());
        userVO.setCreateTime(user.getCreateTime());
        userVO.setEmail(user.getEmail());
        userVO.setNickname(user.getNickname());
        userVO.setRole(role);
        return userVO;
    }

    @Override
    public ResultBean addUser(String email, int roleId) {
        User user=new User();
        user.setEmail(email);
        user.setRoleId(roleId);
        user.setStatus(0);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        try {
            userMapper.insert(user);
            Session session = CreateSession();
            Transport ts = session.getTransport();
            String content="欢迎！请等待管理员激活您的账号";
            ts.connect("smtp.qq.com","375359554@qq.com","orfgypplgcoibjei");
            String[] to={email};
            Message message = createSimpleMail(session,"375359554@qq.com",to,"长虹智能手环",content);
            ts.sendMessage(message, message.getAllRecipients());
            return new ResultBean();
        }catch (DuplicateKeyException e){
            return new ResultBean(e,ResultBean.CONFLICT);
        }catch (NoSuchProviderException e){
            return new ResultBean(e,ResultBean.BAD_REQUEST);
        }catch (MessagingException e){
            return new ResultBean(e,ResultBean.CONFLICT);
        }catch (Exception e){
            return new ResultBean(e,ResultBean.CONFLICT);
        }
    }

    @Override
    public ResultBean updatePassword(HttpServletRequest request, String oldPassword, String newPassword, String confirmPassword) {
        if(!newPassword.equals(confirmPassword)){
            UserException userException=new UserException("两次密码不一致");
            return new ResultBean(userException,ResultBean.CONFLICT);
        }
        UserVO userVO=this.getUser(request);
        String email=userVO.getEmail();
        UserExample example=new UserExample();
        example.createCriteria().andEmailEqualTo(email).andIdEqualTo(userVO.getId());

        User user=userMapper.selectByExample(example).get(0);
        if(!oldPassword.equals(user.getPassword())){
            UserException userException=new UserException("密码不正确");
            return new ResultBean(userException,ResultBean.BAD_REQUEST);
        }

        User user1=new User();
        user1.setPassword(newPassword);
        userMapper.updateByExampleSelective(user1,example);
        return new ResultBean(1);
    }

    //发送邮件模块
    public Session CreateSession()
    {
        Properties prop = new Properties();
        prop.setProperty("mail.host","smtp.qq.com");
        prop.setProperty("mail.transport.protocol", "smtp");
        prop.setProperty("mail.smtp.auth", "true");

        Session session = Session.getInstance(prop);
        session.setDebug(true);
        return session;
    }
    public MimeMessage createSimpleMail(Session session, String From, String []to, String subject, String content) throws Exception
    {
        MimeMessage message = new MimeMessage(session);
        //指定邮件的发件人
        message.setFrom(new InternetAddress(From));
        //指定一个邮件的收件人
        if(to.length==0)
        {
            return null;
        }
        for(String recipient:to)
        {
            message.addRecipients(Message.RecipientType.BCC, recipient);
        }

        message.setSubject(subject);
        message.setContent(content,"text/html;charset=UTF-8");
        return message;
    }


}
